package com.yy.base.common.action;

import com.mes.entity.User;
import com.yy.base.page.Page;
import com.yy.base.util.SessionInfo;
import com.yy.base.util.UserUtil;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionChartFilter implements Filter {
	
	public void destroy() {
	}
	
	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest rep, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)rep;
		HttpServletResponse response = (HttpServletResponse)res;
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(UserUtil.USERSESSION);
		if (user != null) {
			SessionInfo.setUser(user);
		}
		initPageSplit(request);
		chain.doFilter(request, response);
	}
	
	/**
	 * 初始化分页查询数据
	 */
	private void initPageSplit(HttpServletRequest request) {
		Page page = SessionInfo.getPage();
		try {
			page.setPageIndex(Integer.parseInt(request.getParameter("page")));
			if (request.getParameter("rows") != null && request.getParameter("limit") == null) {
				page.setPageSize(Integer.parseInt(request.getParameter("rows")));
			} else {
				page.setPageSize(Integer.parseInt(request.getParameter("limit")));
			}
		} catch (Exception e) {
			try {
				page.setPageIndex(Integer.parseInt(request.getParameter("pageIndex")));
				page.setPageSize(Integer.parseInt(request.getParameter("pageSize")));
			} catch (Exception ex) {
			}
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
	}
}